package cn.dinkevin.xui.widget.surface;

import android.content.Context;
import android.graphics.PixelFormat;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import cn.dinkevin.xui.util.LogUtil;

/**
 * Created by ChengPengFei on 2017/1/4 0004.
 */

public class VideoSurfaceViewSpecial extends SurfaceView implements SurfaceHolder.Callback {

    private SurfaceHolder holder;
    private boolean isSurfaceViewAvailable = false; // 当前 SurfaceView 是否可用

    /**
     * SurfaceView 监听
     */
    public interface SurfaceViewListener {

        /**
         * 当 SurfaceView 可用回调
         *
         * @param holder
         */
        void onSurfaceCreated(SurfaceHolder holder);

        /**
         * 当 SurfaceView 销毁时回调
         *
         * @param holder
         */
        void onSurfaceDestroyed(SurfaceHolder holder);
    }

    private SurfaceViewListener listener;

    /**
     * 绑定 SurfaceView 事件监听回调
     *
     * @param listener SurfaceViewListener
     */
    public void setOnSurfaceViewListener(SurfaceViewListener listener) {
        this.listener = listener;
    }

    public VideoSurfaceViewSpecial(Context context) {
        this(context, null);
    }

    public VideoSurfaceViewSpecial(Context context, AttributeSet attrs) {
        super(context, attrs);

        if (attrs == null) return;

        setZOrderOnTop(true);
        setZOrderMediaOverlay(true);
        holder = getHolder();
        holder.setFormat(PixelFormat.TRANSPARENT);                  //translucent半透明 transparent透明
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        holder.addCallback(this);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
//        Canvas canvas = holder.lockCanvas();
//        canvas.drawColor(Color.BLACK);
//        holder.unlockCanvasAndPost(canvas);

        isSurfaceViewAvailable = true;

        if (this.listener != null)
            this.listener.onSurfaceCreated(holder);
        LogUtil.d("surfaceCreated");
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        LogUtil.d("surfaceChanged");
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        isSurfaceViewAvailable = false;
        if (listener != null)
            listener.onSurfaceDestroyed(holder);
        LogUtil.d("surfaceDestroyed");
    }

    /**
     * 获取当前 SurfaceView 是否可用
     *
     * @return
     */
    public boolean isSurfaceViewAvailable() {
        return isSurfaceViewAvailable;
    }
}
